#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>

#define PWM "/sys/class/pwm/pwmchip0"
#define PWM_PATH "/sys/class/pwm/pwmchip0/pwm0" // 替换为你的 PWM 设备路径

void write_to_file(const char *path, const char *value) {
    FILE *file = fopen(path, "w");
    if (file == NULL) {
        perror("Failed to open file");
        exit(EXIT_FAILURE);
    }
    fprintf(file, "%s", value);
    fclose(file);
}

void signal_handler(int arg)
{
    // 禁用 PWM
    write_to_file(PWM_PATH "/enable", "0");

    // 取消导出 PWM 设备
    write_to_file(PWM "/unexport", "0");

    exit(0);
}

int main() {
    
    signal(SIGINT, signal_handler);

    // 导出 PWM 设备
    write_to_file(PWM "/export", "0");

    // 设置周期为 20ms
    write_to_file(PWM_PATH "/period", "20000000");

    // 启用 PWM
    write_to_file(PWM_PATH "/enable", "1");
    
    while(1){
        // 设置占空比为 19ms
        write_to_file(PWM_PATH "/duty_cycle", "19000000");

        sleep(1);

        // 设置占空比为 18ms
        write_to_file(PWM_PATH "/duty_cycle", "18000000");

        sleep(1);
    }

    return 0;
}
